import { DatabaseService } from '../database'
import { dbErrorInterceptor, dbRequestInterceptor, dbResponseInterceptor, ollamaErrorInterceptor, ollamaRequestInterceptor, ollamaResponseInterceptor } from '../interceptors'
import { OllamaService } from '../ollama'

// 创建服务实例
const ollamaService = new OllamaService()

// 检查 Ollama 实例状态
async function checkOllamaStatus() {
  try {
    const response = await fetch('http://localhost:11434/api/version')
    const data = await response.json()
    console.warn('Ollama 实例状态:', {
      address: 'http://localhost:11434',
      version: data.version,
      status: 'running',
    })
    return true
  } catch (error) {
    console.warn('Ollama 实例未运行或无法访问:', {
      address: 'http://localhost:11434',
      status: 'error',
      error: error instanceof Error ? error.message : '未知错误',
    })
    return false
  }
}

// 检查实例状态
await checkOllamaStatus()

const mockMcpClient = {
  query: async (_sql: string, _params: any[]) => {
    return { rows: [], rowCount: 0, fields: [] }
  },
}
const dbService = new DatabaseService(mockMcpClient)

// 添加拦截器
ollamaService.addInterceptor(ollamaRequestInterceptor)
ollamaService.addInterceptor(ollamaResponseInterceptor)
ollamaService.addInterceptor(ollamaErrorInterceptor)

dbService.addInterceptor(dbRequestInterceptor)
dbService.addInterceptor(dbResponseInterceptor)
dbService.addInterceptor(dbErrorInterceptor)

// 使用示例
async function example() {
  try {
    // 1. 使用 Ollama 生成文本
    const ollamaResponse = await ollamaService.generate({
      model: 'llama2',
      prompt: '请帮我查询用户数据',
      options: {
        temperature: 0.8,
      },
    })

    if (ollamaResponse.code === 200 && ollamaResponse.data) {
      // 2. 解析生成的 SQL 查询
      const generatedQuery = ollamaResponse.data.response

      // 3. 执行数据库查询
      const dbResponse = await dbService.query({
        query: generatedQuery,
        params: [],
      })

      if (dbResponse.code === 200 && dbResponse.data) {
        // 4. 处理查询结果
        const results = dbResponse.data.rows
        console.warn('查询结果:', results)
      }
    }

    // 5. 使用流式生成
    await ollamaService.generateStream(
      {
        model: 'llama2',
        prompt: '请分析这些数据',
      },
      chunk => {
        console.warn('生成内容:', chunk.response)
      }
    )

    // 6. 执行事务
    const transactionResponse = await dbService.transaction([
      {
        query: 'INSERT INTO users (name, email) VALUES ($1, $2)',
        params: ['John Doe', 'john@example.com'],
      },
      {
        query: 'UPDATE user_count SET count = count + 1',
      },
    ])

    if (transactionResponse.code === 200) {
      console.warn('事务执行成功:', transactionResponse.data)
    }
  } catch (error) {
    console.error('执行出错:', error)
  }
}

// 运行示例
example()
